/**
 * 
 */
package com.smartodo.web.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Logger;
import org.owasp.esapi.ValidationErrorList;
import org.owasp.esapi.errors.EncryptionException;
import org.owasp.esapi.errors.ValidationException;

import com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;
import com.smartodo.utils.DbUtils;
import com.smartodo.utils.WebUtils;
import com.smartodo.vo.CreateAccountVO;

/**
 * @author Pawan Singh
 *
 */
public class CreateAccountValidate extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	
	private static final Logger logger =  ESAPI.getLogger("CreateAccountValidate");
	
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public CreateAccountValidate() {
		super();
	} 

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		logger.info(Logger.EVENT_SUCCESS, "Invoked doPost");
		
		ValidationErrorList errorList = WebUtils.getErrors();
		CreateAccountVO vo = new CreateAccountVO();
		
		String fname = ESAPI.validator().getValidInput("First Name", request.getParameter("fname"), "AccountName", 255, false, errorList);
		String lname = ESAPI.validator().getValidInput("Last Name", request.getParameter("lname"), "AccountName", 255, false, errorList);
		String loginId = ESAPI.validator().getValidInput("Login Id", request.getParameter("loginid"), "LoginId", 255, false, errorList);
		String pass1 = ESAPI.validator().getValidInput("Password1", request.getParameter("pass1"), "AccountName", 255, false, errorList);
		String pass2 = ESAPI.validator().getValidInput("Password2", request.getParameter("pass2"), "AccountName", 255, false, errorList);
		String secQuestion = ESAPI.validator().getValidInput("Security Question", request.getParameter("selection"), "SecurityQuestion", 255, false, errorList);
		String secanswer = ESAPI.validator().getValidInput("Security Answer", request.getParameter("secanswer"), "AccountName", 255, false, errorList);
		String userCaptchaResponse = ESAPI.validator().getValidInput("Word Verification", request.getParameter("jcaptcha"), "AccountName", 255, false, errorList);
		String location = ESAPI.validator().getValidInput("Location", request.getParameter("loc"), "SecurityQuestion", 255, false, errorList);
		
		//make sure both passwords are same
		if (!pass1.equals(pass2)) errorList.addError("Passwords donot match", new ValidationException("Passwords do not match","Passwords do not match"));
		
		//validate captcha
		boolean captchaPassed = SimpleImageCaptchaServlet.validateResponse(request, userCaptchaResponse);
		
		if(captchaPassed){
			
			//if all the input validation & captcha passed then set all the fields in the database using the VO
			vo.setFname(fname);
			vo.setLname(lname);
			vo.setLoginId(loginId);
			try {
				vo.setPassword(ESAPI.authenticator().hashPassword(loginId, pass1));
			} catch (EncryptionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			vo.setSecAnswere(secanswer);
			vo.setSecQuestion(secQuestion);
			vo.setLocation(location);
			
		}else{
			//add error to display in the JSP
			errorList.addError("Captcha error", new ValidationException("Please enter correct word verification","Captcha Error"));
		}
		
		//add errorList to WebUtils
		WebUtils.setErrors(errorList);
		
		//fail if any validation errors
		if (!errorList.isEmpty()) {
			RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/create_account.jsp");
			dispatcher.forward(request, response);
			return;
		}
		if(DbUtils.addUser(vo)) {
			WebUtils.addMessage("Account created successfully!");
		} else {
			errorList.addError("Error creating account", new ValidationException(loginId+" is not available. Please try with another Id.","SQLException"));
			WebUtils.setErrors(errorList);
			RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/create_account.jsp");
			dispatcher.forward(request, response);
			return;
		}
		
		//if no errors then forward to account login
		RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/jsp/home.jsp");
		dispatcher.forward(request, response);
		return;
	}
}
